import Vue from 'vue'
import axios from 'axios'
import { Message } from 'element-ui'

// 发送请求前配置请求及参数  request 拦截器
axios.interceptors.request.use((config) => {
    var arr = document.cookie.match(new RegExp('(^| )login_token=([^;]*)(;|$)'));
    var token = (arr != null) ? unescape(arr[2]) : null;
    if(config.url.indexOf('?') > -1){
        config.url += '&_token=' + token
    }else{
        config.url += '?_token=' + token
    }
    config.headers['X-Requested-With'] = 'XMLHttpRequest'
    return config; 
}, error => {
    return Promise.reject(error);
})

// response 拦截器
axios.interceptors.response.use(response => {
    const res = response.data;
   if(res.code && res.code != 200){
        Message({
            message: res.message,
            type: 'error',
            duration: 3 * 1000
        });
        return Promise.reject('error');
    }else{
        return response.data;
    }
}, error => {
    console.log(error)
    Message({
        message: error.message,
        type: 'error',
        duration: 3 * 1000
    })
    return Promise.reject(error)
})

Vue.prototype.$axios = axios